//
//  UIImageView+hehe.m
//
//  Created by Robin on 15/6/3.
//  Copyright (c) 2015年 MeiYou. All rights reserved.
//

#import "UIImageView+MY.h"
#import "NSString+Topic.h"

static char imageTypeKey;

@implementation UIImageView (MY)

-(MYImageType)imageType
{
    NSNumber *value = objc_getAssociatedObject(self, &imageTypeKey);
    if(value == nil){
        return MYImageTypeDefault;
    }
    return value.integerValue;
}

-(void)setImageType:(MYImageType)imageType
{
    objc_setAssociatedObject(self, &imageTypeKey, @(imageType), OBJC_ASSOCIATION_ASSIGN);
    [self updateWithImageType:imageType];
}

-(void)updateWithImageType:(MYImageType)type
{
    self.backgroundColor = HEXCOLOR(HSColorLightGray);
    self.loadedViewContentMode = UIViewContentModeScaleAspectFill;
    self.placeholderContentMode = UIViewContentModeCenter;
    self.clipsToBounds = YES;
    self.contentMode = UIViewContentModeScaleAspectFill;
    self.backgroundColor = [UIColor clearColor];//背景色
//    self.imageType = type;
    switch (type) {
        case MYImageTypeSmallPic:
        {
            self.placeholderImageName = @"bg";
            self.failureImageName = @"bg_lk";
            self.placeholderContentMode = UIViewContentModeScaleToFill;
        }
            break;
        case MYImageTypePic:
        {
            self.placeholderImageName = @"bg";
            self.failureImageName = @"bg_lk";
        }
            break;
        case MYImageTypeHead:
        {
            self.contentMode = UIViewContentModeScaleToFill;
            self.placeholderImageName = @"unloginAvatar3";
            self.failureImageName = @"unloginAvatar3";
            self.isHideProgress = YES;
            [self imageBorderWithCornerRadius:self.height / 2. borderColor:[UIColor whiteColor] andBorderWidth:0];
        }
        case MYImageTypeSmallHead:{
            self.placeholderImageName = @"unloginAvatar3";
            self.failureImageName = @"unloginAvatar3";
            self.placeholderContentMode = UIViewContentModeScaleToFill;
            self.isHideProgress = YES;
            [self imageBorderWithCornerRadius:self.height / 2. borderColor:[UIColor whiteColor] andBorderWidth:0];
        }
            break;
        default:
            break;
    }
}

#pragma mark - init method

-(instancetype)initWithImageType:(MYImageType)type
{
    return [self initWithFrame:CGRectZero imageType:type];
}

-(instancetype)initWithFrame:(CGRect)frame imageType:(MYImageType)type
{
    UIImageView *img = [[YYAnimatedImageView alloc]initWithFrame:frame];
//    [img updateWithImageType:type];
    img.imageType = type;
    return img;
}

+(instancetype)avatarWithFrame:(CGRect)frame
                   imageType:(MYImageType)type
                 borderColor:(UIColor *)borderColor
                 borderWidth:(CGFloat)borderWidth
{
    UIImageView *img = [[YYAnimatedImageView alloc]initWithFrame:frame];
    img.loadedViewContentMode = UIViewContentModeScaleAspectFill;
    img.clipsToBounds = YES;
    img.backgroundColor = [UIColor clearColor];//背景颜色
    img.placeholderImageName = @"unloginAvatar3";
    img.failureImageName = @"unloginAvatar3";
    img.isHideProgress = YES;
    if(type == MYImageTypeHead){
        img.contentMode = UIViewContentModeScaleToFill;
        img.placeholderContentMode = UIViewContentModeCenter;
    }
    else if(type == MYImageTypeSmallHead){
        img.contentMode = UIViewContentModeScaleAspectFill;
        img.placeholderContentMode = UIViewContentModeScaleToFill;
    }
    [img imageBorderWithCornerRadius:img.height / 2. borderColor:borderColor andBorderWidth:borderWidth];
    return img;
}

#pragma mark - method

static NSString *const ALiYunPrefix = @"?x-oss-process=image/resize,";

- (void)my_setImageUrl:(NSString *)imageUrl sacleType:(MYImageScaleType)scaleType
{
    NSString *isOn = [[NSUserDefaults standardUserDefaults] objectForKey:NoPicKey];
    if ([isOn isEqualToString:@"1"] && [MYAppHelper shareHelper].networkStatus != AFNetworkReachabilityStatusReachableViaWiFi) {
        return [self lk_setImageURL:@""];
    }
    if (scaleType == MYImageScaleTypeOrign || [imageUrl containsString:ALiYunPrefix]) {
        [self lk_setImageURL:imageUrl];
        return;
    }
    NSString *subfix = @"";
    CGSize size = [imageUrl my_lastComponentOriginalImageSize];
    MYImageScaleType _type = scaleType;
    if (size.width != 0 && size.height !=0 && size.height < size.width) {
        //图片展示大部分会有mode，如果高小于宽，可能导致图片拉伸糊掉，所以用最大尺寸
        _type = scaleType < MYImageScaleTypeOrign ? MYImageScaleTypeHeadBig : MYImageScaleTypePicBig;
    }
    switch (_type) {
        case MYImageScaleTypeHeadSmall:
            subfix = @"w_150";
            break;
        case MYImageScaleTypeHeadMiddle:
            subfix = @"w_200";
            break;
        case MYImageScaleTypeHeadBig:
            subfix = @"w_250";
            break;
        case MYImageScaleTypePicSmall:
            subfix = [NSString stringWithFormat:@"w_%d", (int)(ScreenWidth * 0.4)];
            break;
        case MYImageScaleTypePicMiddle:
            subfix = [NSString stringWithFormat:@"w_%d", (int)(ScreenWidth * 0.8)];
            break;
        case MYImageScaleTypePicBig:
            subfix = [NSString stringWithFormat:@"w_%d", (int)(ScreenWidth * 1.2)];
            break;
        default:
            break;
    }
    [self lk_setImageURL:[[imageUrl stringByAppendingString:ALiYunPrefix] stringByAppendingString:subfix]];
}

-(void)my_setImage:(id)image
{
    NSString *isOn = [[NSUserDefaults standardUserDefaults] objectForKey:NoPicKey];
    if ([isOn isEqualToString:@"1"] && [MYAppHelper shareHelper].networkStatus != AFNetworkReachabilityStatusReachableViaWiFi) {
        return [self lk_setImageURL:@""];
    }
    if([image isKindOfClass:[NSString class]]){
        if([image hasPrefix:@"https"] || [image hasPrefix:@"http"] || [image hasPrefix:@"ftp"]){
            [self lk_setImageURL:image];
        }
        else if(![image isNotBlank]){
            [self lk_setImageURL:image];
        }
        else{
            self.image = [UIImage imageNamed:image];
        }
    }
    else if([image isKindOfClass:[UIImage class]]){
        self.image = image;
    }
    else if([image isKindOfClass:[NSURL class]]){
        [self lk_setImageURL:image];
    }
    else{
        UIImage *image = [UIImage imageNamed:self.placeholderImageName];
        if (self.bounds.size.width < image.size.width || self.bounds.size.height < image.size.height){
            self.contentMode = UIViewContentModeScaleAspectFit;
        }
        else{
            self.contentMode = UIViewContentModeCenter;
        }
        self.image = image;
    }
}

/**
 *  图片圆角边框
 *
 *  @param radius      圆角半径
 *  @param borderColor 边框原色
 *  @param borderWidth 边框宽
 */
- (void)imageBorderWithCornerRadius:(CGFloat)radius borderColor:(UIColor *)borderColor andBorderWidth:(CGFloat)borderWidth
{
    CGRect rect = self.bounds;
    
    //Make round
    // Create the path for to make circle
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:rect
                                                   byRoundingCorners:UIRectCornerAllCorners
                                                         cornerRadii:CGSizeMake(radius, radius)];
    
    // Create the shape layer and set its path
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    
    maskLayer.frame = rect;
    maskLayer.path  = maskPath.CGPath;
    
    // Set the newly created shape layer as the mask for the view's layer
    self.layer.mask = maskLayer;
    
    //Give Border
    //Create path for border
    UIBezierPath *borderPath = [UIBezierPath bezierPathWithRoundedRect:rect
                                                     byRoundingCorners:UIRectCornerAllCorners
                                                           cornerRadii:CGSizeMake(radius, radius)];
    // Create the shape layer and set its path
    CAShapeLayer *borderLayer = [CAShapeLayer layer];
    
    borderLayer.frame       = rect;
    borderLayer.path        = borderPath.CGPath;
    borderLayer.strokeColor = borderColor.CGColor;
    borderLayer.fillColor   = [UIColor clearColor].CGColor;
    borderLayer.lineWidth   = borderWidth;

    //Add this layer to give border.
    [self.layer addSublayer:borderLayer];
}

@end
